﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using MyLocalChurch.Constants;
using MyLocalChurch.Models;

namespace MyLocalChurch.Business
{
    public static class PhotoManager
    {
        public static Photo CreatePhotoFromFileUploadOrSession(FileUpload fileUpload, HttpContext context)
        {
            var imgData = GetImageDataFromFileUploadOrSession(fileUpload, context);
            if (imgData == null || imgData.Length == 0)
                return null;

            return new Photo
                {
                    Name = fileUpload.FileName,
                    ContentType = fileUpload.PostedFile.ContentType,
                    ImageData = imgData,
                    CreatedBy = SystemConstants.User,
                    CreatedDate = DateTime.Now
                };
        }

        public static byte[] GetImageDataFromFileUploadOrSession(FileUpload fileUpload, HttpContext context)
        {
            if (fileUpload.PostedFile == null)
                return null;

            var imgStream = fileUpload.PostedFile.InputStream;
            var imgLength = fileUpload.PostedFile.ContentLength;
            var imgData = new byte[imgLength];
            
            imgStream.Read(imgData, 0, imgLength);

            if (imgData.Length == 0 && context.Session[ImageHandler.SessionName] != null)
                imgData = (byte[])HttpContext.Current.Session[ImageHandler.SessionName];

            return imgData;
        }
    }
}